package fun.sboy.headacheMemo.controller;

import fun.sboy.headacheMemo.util.ResultUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;

@RequestMapping("/commons")
@RestController
public class CommonsController {

    @Value("${savePath}")
    private String savePath;
    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @PostMapping("/upload")
    public ResultUtils uploadFile(MultipartFile file) throws IOException {
        System.out.println("访问了上传接口");
        //保存文件
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String suffix = file.getOriginalFilename().split("\\.")[1];
        String fileName = String.format("%s.%s", uuid, suffix);
        System.out.println(fileName);
        System.out.println(savePath);
        file.transferTo(new File(savePath + "/" + fileName));
        return ResultUtils.success(fileServerUrl + "/commons/download/" + fileName);
    }

    @GetMapping("/download/{fileName:..+}")
    public void downloadFile(@PathVariable("fileName") String fileName, HttpServletResponse resp) throws IOException {
        String filePath = String.format("%s/%s", savePath, fileName);
        FileInputStream fileInputStream = new FileInputStream(filePath);
        ServletOutputStream outputStream = resp.getOutputStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);

        byte[] bytes = new byte[1024];
        int len;
        while ((len = bufferedInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        outputStream.flush();

        //释放资源
        fileInputStream.close();
        outputStream.close();
        bufferedInputStream.close();
    }
}
